﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Windows.Threading;

namespace VkClientIM.Logic
{
	public class NotifyCollectionChangedProxy<T, W>
	: IList<W>, INotifyCollectionChanged
	where T : IList<W>, INotifyCollectionChanged
	{
		private T _list;
		public NotifyCollectionChangedProxy(T list)
		{
			_list = list;
			list.CollectionChanged +=
				delegate(object o, NotifyCollectionChangedEventArgs args)
				{
					if (CollectionChanged != null)
					{
						foreach (var @delegate in CollectionChanged.GetInvocationList())
						{
							DispatcherObject dispatcherObject = @delegate.Target as DispatcherObject;
							if (dispatcherObject != null && dispatcherObject.CheckAccess() == false)
							{
								// Invoke handler in the target dispatcher's thread
								dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, @delegate, o, args);
							}
							else
							{
								CollectionChanged(o, args);
							}
						}

					}
				};
		}

		public event NotifyCollectionChangedEventHandler CollectionChanged;

		public int IndexOf(W item)
		{
			return _list.IndexOf(item);
		}

		public void Insert(int index, W item)
		{
			_list.Insert(index, item);
		}

		public void RemoveAt(int index)
		{
			_list.RemoveAt(index);
		}

		public W this[int index]
		{
			get
			{
				return _list[index];
			}
			set
			{
				_list[index] = value;
			}
		}

		public void Add(W item)
		{
			_list.Add(item);
		}

		public void Clear()
		{
			_list.Clear();
		}

		public bool Contains(W item)
		{
			return _list.Contains(item);
		}

		public void CopyTo(W[] array, int arrayIndex)
		{
			_list.CopyTo(array, arrayIndex);
		}

		public int Count
		{
			get { return _list.Count; }
		}

		public bool IsReadOnly
		{
			get { return false; }
		}

		public bool Remove(W item)
		{
			return _list.Remove(item);
		}

		public IEnumerator<W> GetEnumerator()
		{
			return _list.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return _list.GetEnumerator();
		}
	}
}
